package com.my.screenadapter.myActivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.ajie.lib_base.ft_file.FileIOUtils;
import com.my.screenadapter.Base.BaseActivity;
import com.my.screenadapter.ImgVideoSel.ImageUtils;
import com.my.screenadapter.MyApplication;
import com.my.screenadapter.R;
import com.my.screenadapter.mdir.FileUtils;
import com.my.screenadapter.utils.Base64Util;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import Decoder.BASE64Decoder;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by zyj 2018-12-28
 * Function：intent 其他应用特定功能并返回结果。 netty demo 配合测试
 *
 * Activity 跳转生命周期
 *
 *
 * {@link #intentNewTaskFlag}
 * 测试 FLAG_ACTIVITY_NEW_TASK
 * 2次打开 flag  是 FLAG_ACTIVITY_NEW_TASK  xml 中是默认standard  结果：重新走完整的生命周期
 * 还是在原来的 task 栈中
 *
 */
public class IntentActivity extends BaseActivity {
    @BindView(R.id.btn_intent_other_app)
    Button btnIntentOtherApp;
    @BindView(R.id.btn_intent_other_app_noauto)
    Button btnIntentOtherAppNoauto;
    @BindView(R.id.btn_intent_matchface)
    Button btnIntentMatchface;
    @BindView(R.id.iv_receive)
    ImageView ivReceive;
    private Logger logger = Logger.getLogger(IntentActivity.class);

    @Override
    protected void init() {

    }

    //跳转其他activity
    public void intentOtherActivity(View view) {
        startActivity(new Intent(this, StandardActivity.class));
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_intent;
    }

    public void intentOtherAppActivity(View view) {
        Intent intent = new Intent();
        intent.setAction("MatchThread");
        intent.setType("text/plain");
        Bundle bundle = new Bundle();
        IntentBean intentBean = new IntentBean();
        intentBean.setType(0);
        intentBean.setOrder("client order");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", 0);//0 自动 1手动
            jsonObject.put("order", "client order");//0 自动 1手动
        } catch (JSONException e) {
            e.printStackTrace();
        }
        logger.info("client send info== " + jsonObject.toString());
        bundle.putString("data", jsonObject.toString());
        intent.putExtras(bundle);
        startActivityForResult(intent, 101);
    }

    public void intentOtherAppActivityNoAuto(View view) {
        Intent intent = new Intent();
        intent.setAction("MatchThread");
        intent.setType("text/plain");
        Bundle bundle = new Bundle();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", 1);//0 自动 1手动
            jsonObject.put("order", "client order 2");//0 自动 1手动
        } catch (JSONException e) {
            e.printStackTrace();
        }
        logger.info("client send info== " + jsonObject.toString());
        bundle.putString("data", jsonObject.toString());
        intent.putExtras(bundle);
        startActivityForResult(intent, 102);
    }


    public void matchFace1V1(View view) {
        Intent intent = new Intent();
        intent.setAction("MatchFace1V1");
        intent.setType("text/plain");
        Bundle bundle = new Bundle();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", 0);//0 自动 1手动
            jsonObject.put("order", "client order 2");//0 自动 1手动
        } catch (JSONException e) {
            e.printStackTrace();
        }
        logger.info("client send info== " + jsonObject.toString());
        bundle.putString("data", jsonObject.toString());
        intent.putExtras(bundle);
        startActivityForResult(intent, 10303);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        logger.info("requestCode==" + requestCode + "  resultCode==" + resultCode + "   data==" + (data == null));
        if (requestCode == 101 || requestCode == 102 ||requestCode == 10303) {//auto  noauto
            Bundle extras = data.getExtras();
            if (extras != null && resultCode == Activity.RESULT_OK) {
                dealReceiveData(extras);
            }
        } else {
            logger.warn("other....result");
        }
    }

    //处理反馈的数据
    private void dealReceiveData(Bundle extras) {
        if (extras == null){
            logger.error("receive data == null");
            return;
        }
        logger.info("is received data ov"+extras.size());
        String matchResult = extras.getString("matchResult");//success fail
        if ("fail".equals(matchResult)){
            logger.error("matchResult== fail");
            return;
        }else if (!"success".equals(matchResult)){
            logger.error("matchResult== "+matchResult);
            return;
        }
        logger.info("matchResult== success");
        String idcardInfo = extras.getString("idcardInfo");
        logger.warn("idcardinfo==" + idcardInfo);
        String img = extras.getString("img");
        logger.warn("img==" + img);
        if (!TextUtils.isEmpty(img)){
            String realPathFromUri = ImageUtils.getRealPathFromUri(this, Uri.parse(img));
            logger.warn("realPathFromUri==" + realPathFromUri);
            if (!TextUtils.isEmpty(realPathFromUri)){
                ivReceive.setImageBitmap(BitmapFactory.decodeFile(realPathFromUri));
            }
        }
        String json = extras.getString("json");
        FileIOUtils.writeFileFromBytesByStream(new File(IntentActivity.this.getFilesDir().getAbsolutePath()+File.separator+"receiveJson.txt"),json.getBytes());

        logger.warn("json==" + json);
        if (!TextUtils.isEmpty(json)){
            try {
                JSONObject jsonObject = new JSONObject(json);
                String libPhoto = jsonObject.getString("libPhoto");
                logger.warn("libPhoto==" + libPhoto.length());
                if (!TextUtils.isEmpty(libPhoto)){
                    Bitmap bitmap = Base64Util.decodeBase64StrToBitmap(libPhoto);
//                    byte[] bytes = GenerateByte(libPhoto);
                    logger.warn("bitmap bytes==" + bitmap!=null?bitmap.getHeight():null);
                    if (bitmap != null) {
                        ivReceive.setImageBitmap(bitmap);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //base64字符串转化成图片
    public static byte[] GenerateByte(String imgStr) throws IOException {   //对字节数组字符串进行Base64解码并生成图片
//        Boolean Flag = false;
        if (imgStr == null) //图像数据为空
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        //Base64解码
        byte[] b = decoder.decodeBuffer(imgStr);
        return b;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        MatchReceiver.setBrInteractionListener(new MatchReceiver.BRInteraction() {
            @Override
            public void setBundle(Bundle bundle) {
                //接收反馈信息
                dealReceiveData(bundle);
            }
        });
    }

    public void NettyReceiver(View view) {
        Intent intent = new Intent();
        //对应BroadcastReceiver中intentFilter的action
        intent.setAction("NettyReceiver");
        //发送广播
        sendBroadcast(intent);
    }

    public void matchFaceReceiver(View view) {
        Intent intent = new Intent();
//对应BroadcastReceiver中intentFilter的action
        intent.setAction("MatchReceiver");
//发送广播
        sendBroadcast(intent);
    }


    public void intentSingleTopAc(View view) {
        Intent intent = new Intent(this, MSingTopActivity.class);
        intent.putExtra("int1","1");
        startActivity(intent);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent2 = new Intent(IntentActivity.this, MSingTopActivity.class);
                intent2.putExtra("int2","2");
                startActivity(intent2);
            }
        },5000);
    }


    public void intentNewTaskFlag(View view) {
        Log.i(TAG, "intentNewTaskFlag: ");
        Intent intent = new Intent(this, StandardActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        //测试时2次打开 flag  是 FLAG_ACTIVITY_NEW_TASK  xml 中是默认standard  结果：重新走完整的生命周期
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                intentNewTaskFlagInThread(null);
            }
        },3000);
    }

    public void intentNewTaskFlagInThread(View view) {
        Log.i(TAG, "intentNewTaskFlagInThread: ");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "run: thread name "+Thread.currentThread().getName());
                Intent intent = new Intent(MyApplication.getContext(), StandardActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                MyApplication.getContext().startActivity(intent);
            }
        }).start();
    }
}
